package com.yao.smy.service;

import com.yao.smy.domain.Equipment;
import com.yao.smy.dto.EquipmentDTO;
import com.yao.smy.repository.EquipmentRepository;
import com.yao.smy.repository.VisitorDeviceRecordRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class EquipmentServiceImpl implements EquipmentService {

    @Autowired
    private EquipmentRepository equipmentRepository;

    @Autowired
    private VisitorDeviceRecordRepository visitorDeviceRecordRepository;

    @Override
    public void addEquipment(Equipment equipment) {
        equipmentRepository.save(equipment);
    }

    @Override
    public void deleteEquipment(String ip) {
        equipmentRepository.deleteById(ip);
    }

    @Override
    public void updateEquipment(Equipment equipment) {
        equipmentRepository.save(equipment);
    }

    @Override
    public EquipmentDTO getEquipment(String ip) {
        Equipment equipment = equipmentRepository.findById(ip).orElse(null);

        return toDto(equipment);
    }

    @Override
    public List<EquipmentDTO> getAllEquipments() {
        List<Equipment> equipments = equipmentRepository.findAll();
        List<EquipmentDTO> equipmentDTOs = new ArrayList<>();
        for (Equipment equipment : equipments) {
            equipmentDTOs.add(toDto(equipment));
        }
        return equipmentDTOs;
    }

    private EquipmentDTO toDto(Equipment equipment) {
        if (equipment == null) {
            return null;
        }
        EquipmentDTO equipmentDTO = new EquipmentDTO();
        BeanUtils.copyProperties(equipment, equipmentDTO);

        // 查询总访问次数和今日访问次数
        int totalVisits = visitorDeviceRecordRepository.countByDeviceIp(equipment.getIp());
        int todayVisits = visitorDeviceRecordRepository.countByDeviceIpAndAccessTimeAfter(equipment.getIp(), LocalDateTime.now().with(LocalTime.MIN));

        equipmentDTO.setTotalVisits(totalVisits);
        equipmentDTO.setTodayVisits(todayVisits);
        return equipmentDTO;
    }
}
